package quick.start.core.async;

import quick.start.core.ApplicationBase;
import quick.start.core.extend.ToastExtend;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;

public abstract class DefaultAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

	private Context mContext;
	private String mErrorMsg;
	private Exception mException;
	private Waitting mWaitting;
	
	public DefaultAsyncTask(Context context){
		mContext = context;
	}
	
	public DefaultAsyncTask(IWaitting waitting){
		this(waitting, false);
	}
	
	public DefaultAsyncTask(IWaitting waitting, boolean show){
		super();
		mContext = waitting.getWaittingContext();
		if(show){
			mWaitting = waitting.getWatting();
		}
	}
	
	public Context getContext(){
		return mContext;
	}
	
	public void executeParallelly(Params... params){
		if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB){
			execute(params);
		}else{
			executeOnExecutor(THREAD_POOL_EXECUTOR, params);
		}
	}
	
	protected Exception getException(){
		return mException;
	}
	
	protected void onHandleError(String errorMessage){
		ToastExtend.instance(ApplicationBase.getApplication()).setText(errorMessage).show();
	}
	
	protected abstract Result onLoad(Params... params) throws Exception;
	protected abstract void onUI(Result result);
	
	
	@Override
	protected void onPostExecute(Result result) {
		if(!isCancelled()){
			if(null != mErrorMsg){
				onHandleError(mErrorMsg);
			}else{
				onUI(result);
			}
		}
		
		if(null != mWaitting){
			try{
				mWaitting.p();
			}catch(Exception e){
				
			}
		}
	}

	@Override
	protected void onPreExecute() {
		if(null != mWaitting){
			try{
				mWaitting.p();
			}catch(Exception e){
				
			}
		}
	}

	@Override
	protected Result doInBackground(Params... params) {
		Result result = null;
		try{
			result = onLoad(params);
		}catch(Exception e){
			e.printStackTrace();
			mException = e;
			mErrorMsg = e.getMessage();
		}
		return result;
	}

}
